package com.mjlf.akka.simple;

import akka.actor.*;

/**
 * @ClassName StopActor
 * @auther mjlf
 * @Date 2019/8/5 14:16
 * @Description 监控停止
 */
public class StopActor {

    static class WorkerActor extends AbstractActor{
        @Override
        public Receive createReceive() {
            return receiveBuilder().matchAny(msg -> {
                System.out.println(msg);
                Thread.sleep(2000);
                System.out.println("over");
            }).build();
        }

        @Override
        public void postStop() throws Exception {
            System.out.println("postStop");
            super.postStop();
        }
    }

    static class WatchActor extends AbstractActor{
        ActorRef worker = null;

        @Override
        public void preStart() throws Exception {
            worker = getContext().actorOf(Props.create(WorkerActor.class), "workerActor");
            //监控child, unwatch可以解除监控
            getContext().watch(worker);
        }

        @Override
        public void postStop() throws Exception {
            System.out.println("WatchActor postStop");
        }
        @Override
        public Receive createReceive() {
            return receiveBuilder().matchEquals("StopWorker", msg->{
               getContext().stop(worker);
            }).match(String.class, msg->{
                worker.forward(msg, getContext());
            }).match(Terminated.class, t->{
                System.out.println("监控到" + t.getActor() + "停止了");
            }).build();
        }
    }

    public static void main(String[] args) {
        ActorSystem system = ActorSystem.create();
        ActorRef watchActor = system.actorOf(Props.create(WatchActor.class));

        watchActor.tell("hell", ActorRef.noSender());
        watchActor.tell("StopWorker", ActorRef.noSender());
        watchActor.tell(PoisonPill.getInstance(),ActorRef.noSender());
//        watchActor.tell("hell", ActorRef.noSender());
    }
}
